package tech.bmatch.redpack.service.impl;

import org.springframework.stereotype.Component;
import tech.bmatch.common.util.IDUtil;
import tech.bmatch.redpack.model.*;
import tech.bmatch.redpack.param.CreateRedPackParam;
import tech.bmatch.redpack.service.RedPackService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 红包服务的实现类
 */
@Component
public class RedPackServiceImpl extends RedPackServiceFileStoreImpl {
    private static List<RedPack> caches = new ArrayList<>();

    private static Map<String, String> merchantCache = new HashMap<>();

    static {
        merchantCache.put("test001", "肯德基");
        merchantCache.put("test002", "麦当劳");
        merchantCache.put("test003", "院子餐厅");
    }

    @Override

    public RedPack create(CreateRedPackParam createRedPackParam) {
        RedPack redPack = null;

        if (createRedPackParam.getCouponType().equals(CouponType.MONEYOFF)) {
            MonenyOffRedPack monenyOffRedPack = new MonenyOffRedPack();
            initRedPack(createRedPackParam, monenyOffRedPack);
            monenyOffRedPack.setTotalAmount(createRedPackParam.getTotalAmount() * 100);
            monenyOffRedPack.setMerchantId(createRedPackParam.getMerchantId());
            redPack = monenyOffRedPack;
        } else {
            redPack = new RedPack();
            initRedPack(createRedPackParam, redPack);
        }

        add(redPack);
        return redPack;
    }

    private void initRedPack(CreateRedPackParam createRedPackParam, RedPack redPack) {
        redPack.setId(IDUtil.getId());
        redPack.setGmtCreated(new Date());
        redPack.setGmtModified(new Date());
        redPack.setCouponType(createRedPackParam.getCouponType());
        redPack.setType(createRedPackParam.getRedPackType());
        redPack.setValidity(createRedPackParam.getValidity());
        redPack.setAmount(createRedPackParam.getAmount() * 100);


        List<RedPackCondition> conditions = new ArrayList<>();
        redPack.setConditions(conditions);

        createRedPackParam.getConditionIds().forEach(id -> {
            RedPackCondition condition = new RedPackCondition();
            condition.setId(id);
            conditions.add(condition);
        });
    }

    @Override
    public List<RedPack> query(RedPackType redPackType) {
        List<RedPack> list = caches.stream().filter(redPack -> redPack.getType().equals(redPackType)).collect(Collectors.toList());

        list.stream().filter(redPack -> redPack.getCouponType().equals(CouponType.MONEYOFF)).forEach(redPack -> {
            MonenyOffRedPack monenyOffRedPack = (MonenyOffRedPack) redPack;
            monenyOffRedPack.setMerchantName(merchantCache.get(monenyOffRedPack.getMerchantId()));
        });
        return list;
    }

    public void add(RedPack redPack){
        if(redPack == null) return;
        caches.add(redPack);
        store(caches);
    }

}
